package com.example.goodrubish.Fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.example.goodrubish.API.Okhttp_work;
import com.example.goodrubish.Garbage.HarmwasteActivity;
import com.example.goodrubish.Garbage.KitchenActivity;
import com.example.goodrubish.Garbage.OtherActivity;
import com.example.goodrubish.Garbage.QuizActivity;
import com.example.goodrubish.R;
import com.example.goodrubish.Garbage.RecycleActivity;
import com.example.goodrubish.Garbage.SortActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SortFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SortFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private LinearLayout notificationContainer1,notificationContainer2,notificationContainer3,notificationContainer4;
    private RelativeLayout fabContainer;
    private float initialX;
    private float initialY;
    private float initialTouchX;
    private float initialTouchY;
    public static JSONObject News_JSON;
    String url_garbagenews="http://api.tianapi.com/lajifenleinews/index?key=8edca382d393d0c5f84996d0e8946b96&num=";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public SortFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NewsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SortFragment newInstance(String param1, String param2) {
        SortFragment fragment = new SortFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.activity_sort, container, false);
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        fabContainer = getActivity().findViewById(R.id.fab_container);
        notificationContainer1 = getActivity().findViewById(R.id.notification_container1);
        notificationContainer2 = getActivity().findViewById(R.id.notification_container2);
        notificationContainer3 = getActivity().findViewById(R.id.notification_container3);
        notificationContainer4 = getActivity().findViewById(R.id.notification_container4);

        // 设置点击事件
        notificationContainer1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击事件
                startActivity(new Intent(getActivity(), RecycleActivity.class));

            }
        });
        // 设置点击事件
        notificationContainer2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击事件
                startActivity(new Intent(getActivity(), HarmwasteActivity.class));

            }
        });
        // 设置点击事件
        notificationContainer3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击事件
                startActivity(new Intent(getActivity(), KitchenActivity.class));

            }
        });
        // 设置点击事件
        notificationContainer4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击事件
                startActivity(new Intent(getActivity(), OtherActivity.class));


            }
        });
        fabContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击事件
                startActivity(new Intent(getActivity(), QuizActivity.class));
            }
        });

        fabContainer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 记录初始位置
                        initialX = fabContainer.getX();
                        initialY = fabContainer.getY();
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();
                        return false; // 返回false表示事件已被处理

                    case MotionEvent.ACTION_MOVE:
                        // 计算新的位置
                        float newX = initialX + (event.getRawX() - initialTouchX);
                        float newY = initialY + (event.getRawY() - initialTouchY);

                        // 更新容器的位置
                        fabContainer.setX(newX);
                        fabContainer.setY(newY);
                        return true; // 返回true表示事件已被处理

                    case MotionEvent.ACTION_UP:
                        // 可以在这里处理释放时的逻辑
                        return false; // 返回true表示事件已被处理
                }
                return false;
            }
        });
    }
    public void intn_search() {
        View view = getActivity().getWindow().peekDecorView();
        if (view != null) {//这里是网络访问的代码，获取服务
            InputMethodManager inputmanger = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        initData_search();
    }

    Handler handler_search=new Handler(new Handler.Callback() {//首先通过handler发送信息
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    Toast.makeText(getActivity(),"网络错误",Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    String json=(String)msg.obj;
                    try{
                        News_JSON=new JSONObject(json);
                        Intent intent=new Intent();
                        intent.setClass(getActivity(), SortActivity.class);
                        startActivity(intent);		//进行页面跳转
                        break;
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                default:
                    throw new IllegalStateException("Unexpected value: " + msg.what);
            }
            return false;
        }
    });

    private void initData_search(){
        Okhttp_work.OkHttpGet(url_garbagenews+40, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String content=response.body().string();
                Message message=new Message();
                message.what=1;
                message.obj=content;
                handler_search.sendMessageDelayed(message,1000);
            }
        });
    }

}